const express = require('express')
const Result = require('../../models/Result')
const { decoded } = require('../../utils/index')
const { PRIVATE_KEY, JWT_EXPIRED } = require('../../utils/constant')
const {
  getMenuList,
  editMenu,
  createMenu,
  deleteMenu
} = require('../../services/menu')
const jwt = require('jsonwebtoken')
const jwtAuth = require('../jwt')
// 注册路由
const router = express.Router()
router.use(jwtAuth)

// 生成菜单树
const getMenuTree = (menuList) => {

  // 过滤出一级菜单
  const menuTree = []
  
  // 处理一级菜单
  menuList.forEach(menu => {
    if (menu.menuType === 1){
      menuTree.push({...menu, children: [],buttons: []})
    }
  })

  // 处理二级菜单
  menuList.forEach(menu => {
    if (menu.menuType === 2){
      menuTree.forEach(item => {
        if (item.id === menu.parentId){
          item.children.push(menu)
          item.buttons.push(menu)
        }
       })
    }
  })
  menuTree.forEach(item => {
    if(item.parentId && item.parentId !== null){
      menuTree.forEach(item2 => {
        if (item2.id === item.parentId){
          item2.children.push(item)
        }
      })
    }
  })

  return menuTree.filter(menu => !menu.parentId || menu.parentId === null)
}

//获取菜单列表接口
router.get('/list', function(req, res, next) {
  getMenuList(req.query).then(data => {
    new Result(getMenuTree(data), '菜单信息查询成功').success(res)
  }).catch(err => {
    new Result('菜单信息查询失败').fail(res)
  })
})

//编辑菜单接口
router.post('/edit', function(req, res, next) {
  editMenu(req.body).then(data => {
    new Result('操作成功').success(res)
  }).catch(err => {
    new Result('操作失败').fail(res)
  })
})

//创建菜单接口
router.post('/create', function(req, res, next) {
  createMenu(req.body,decoded(req).cardId).then(data => {
    new Result('操作成功').success(res)
  }).catch(err => {
    new Result('操作失败').fail(res)
  })
})

//删除菜单接口
router.post('/delete', function(req, res, next) {
  deleteMenu(req.body).then(data => {
    new Result('操作成功').success(res)
  }).catch(err => {
    new Result('操作失败').fail(res)
  })
})


module.exports = router